package com.lzm.ydpt.module.mall.activity;

import android.Manifest;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.byt.framlib.base.BaseActivity;
import com.byt.framlib.baseadapter.rv.RvCommonAdapter;
import com.byt.framlib.baseadapter.rv.RvViewHolder;
import com.byt.framlib.basemap.NETLocationListener;
import com.byt.framlib.basemap.NETLocationManager;
import com.byt.framlib.commonutils.GpsUtils;
import com.byt.framlib.commonutils.permission.PermissionReq;
import com.byt.framlib.commonutils.permission.ResultListener;
import com.byt.framlib.commonwidget.LoadingTip;
import com.byt.framlib.commonwidget.NormalTitleBar;
import com.byt.framlib.commonwidget.OnNoDoubleClickListener;
import com.lzm.ydpt.R;
import com.lzm.ydpt.entity.mall.MallAddress;
import com.lzm.ydpt.mvp.contract.SelectLocationContract;
import com.lzm.ydpt.mvp.presenterimpl.SelectLocationPresenterImpl;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * 选择位置
 */
public class SelectLocationActivity extends BaseActivity<SelectLocationPresenterImpl> implements NETLocationListener, SelectLocationContract.View {
    public static final String INP_LOCATION_TYPE = "LOCATION_TYPE";
    public static final String INP_LOCATION_ADDRESS = "LOCATION_ADDRESS";
    @BindView(R.id.ntb_select_address)
    NormalTitleBar ntb_select_address;
    @BindView(R.id.tv_nearby_location_address)
    TextView tv_nearby_location_address;
    @BindView(R.id.tv_location_type)
    TextView tv_location_type;
    @BindView(R.id.tv_location_nearby_select)
    TextView tv_location_nearby_select;
    @BindView(R.id.ltp_select_address)
    LoadingTip ltp_select_address;
    @BindView(R.id.rv_addrss_list)
    RecyclerView rv_addrss_list;
    @BindView(R.id.rl_select_location)
    RelativeLayout rl_select_location;
    private NETLocationManager mManager;
    private AMapLocation mLocation;
    private int locationType = 0; // 正常进来0 附近商铺 1 确认订单 2
    private List<MallAddress> addressList = new ArrayList<>();
    private RvCommonAdapter<MallAddress> adapter = null;

    @Override
    public int getLayoutId() {
        return R.layout.activity_order_select_location;
    }

    @Override
    public SelectLocationPresenterImpl initPreData() {
        return new SelectLocationPresenterImpl(this);
    }

    @Override
    public void initView() {
        locationType = getIntent().getIntExtra(INP_LOCATION_TYPE, 0);
        ntb_select_address.setTitleText(locationType == 0 ? "收获地址" : "选择地址");
        tv_location_nearby_select.setText("重新定位");
        startLocation();
        initAdapter();
    }

    private void initAdapter() {
        rv_addrss_list.setLayoutManager(new LinearLayoutManager(mBContext));
        adapter = new RvCommonAdapter<MallAddress>(mBContext, addressList, R.layout.item_address_list_rv) {
            @Override
            protected void convert(RvViewHolder holder, MallAddress mallAddress, int position) {
//                holder.setText(R.id.tv_address_user_name_phone, );
//                holder.setText(R.id.tv_address_user_detail, );
                holder.setOnClickListener(R.id.img_edt_address, new OnNoDoubleClickListener() {
                    @Override
                    protected void onNoDoubleClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putParcelable(MallAddEdtAddressActivity.INP_ADD_EDT_ADDRESS, mallAddress);
                        openActivity(MallAddEdtAddressActivity.class, bundle);
                    }
                });
            }
        };
        rv_addrss_list.setAdapter(adapter);
    }

    @OnClick({R.id.tv_location_nearby_select, R.id.tv_select_address_add, R.id.rl_select_location})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_location_nearby_select:
                startLocation();
                break;
            case R.id.tv_select_address_add:
                openActivity(MallAddEdtAddressActivity.class);
                break;
            case R.id.rl_select_location:
                if (locationType == 1){
                    setResultOk();
                }
                break;
        }
    }

    /**
     * 开始定位
     */
    public void startLocation() {
        PermissionReq.with(this)
                .permissions(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                .result(new ResultListener() {
                    @Override
                    public void onGranted() {
                        if (!GpsUtils.isOPen(mBContext)) {
                            showShortToast("您未开启手机定位服务，请开启GPS");
                            return;
                        }
                        if (mManager == null) {
                            mManager = new NETLocationManager(mBContext, SelectLocationActivity.this);
                        }
                        mManager.start();
                    }

                    @Override
                    public void onDenied() {
                        showShortToast("未开启位置权限，无法获取位置");
                    }
                }).request();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        try {
            if (null != aMapLocation) {
                stopLocation();
                if (aMapLocation.getErrorCode() == 0) {//可在其中解析amapLocation获取相应内容。
                    mLocation = aMapLocation;
                    tv_nearby_location_address.setText(mLocation.getCountry() + mLocation.getAddress());
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 停止定位
     */
    private void stopLocation() {
        if (mManager != null) {
            mManager.onStop();
        }
    }

    @Override
    public void onStop() {
        if (mManager != null) {
            mManager.onStop();
        }
        super.onStop();
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    @Override
    protected void onDestroy() {
        stopLocation();
        super.onDestroy();
    }

    @Override
    public void onSelectLocation() {

    }

    @Override
    public void showMessage(String message, String method) {

    }

    @Override
    public void showErrorView(String msg) {

    }
}